
// 域名
const baseUrl = 'http://localhost:3000/api/'   

const request = ({ url, data = {}, method = 'POST', ...config } = {}) => new Promise((resolve, reject) => {
	// 打开loading
	uni.showLoading()
	// 获取token
	let __token__ = uni.getStorageSync('token') || ''
	// 配置请求头
	const header = Object.assign({}, config.header, { token: __token__ })
	// 请求url
	const __url__ = baseUrl + url
	
	uni.request({ url: __url__, data: _data, method, header, ...config }).then(response => {
		// 关闭loading
		uni.hideLoading()
		
		let data = response[1].data
		
		// 跟后端约定 统一拦截处理
		switch(data.code) {
			// Success
			case 200:
				data.message && uni.showToast({title: data.message, icon: 'none'})
				return resolve(data.data)
				
			// Fail
			case 500:
				data.message && uni.showToast({title: data.message, icon: 'none'})
				// 返回上一页
				return uni.showModal({
					title: 'error',
					content: data.message,
					success: res => {
						// uni.navigateBack({ delta: 1 })
					}
				})
			// not logged
			case 401:
				data.message && uni.showToast({title: data.message, icon: 'none'})	
				// 返回登录页登录
				return uni.navigateTo({url: '/pages/login/login?redirect=/' + getCurrentPages()[0].route })
				
			default:
				return data.message && uni.showToast({title: data.message, icon: 'none'})
		}
	}).catch( err => {
		// 关闭loading
		uni.hideLoading()
		
		uni.showToast({ title: '接口异常', duration: 2000, icon: 'error' })
		reject(err)
	})
})

// 后端说, 没输入的应该是null, 所以过滤一下
const filterParams = params => Object.entries(params).reduce((obj, [key, val]) => ((obj[key] = val ? val : null), obj), {})

// 导出 post get
const get = (url = '', params ={}, config) => request({ url, params, method: 'GET', ...config })
const post = (url = '', params = {}, config) => request({ url, params, method: 'POST', ...config })
const form_post = (url = '', params = {}, config) => request({ url, params, method: 'POST', ...config })

export default { get, post, form_post, baseUrl }